﻿package at.geoathome.utils.loader
{	
	import flash.display.DisplayObject;
	import flash.events.EventDispatcher;
	import flash.system.LoaderContext;
	import flash.events.Event;
	
	import br.com.stimuli.loading.BulkLoader;
	
	import at.geoathome.interfaces.IFakeDisplayObject;
		
	/**
	* ...
	* @author Georg Kamptner
	* todo: - caching
	*/
	public class AssetLoader extends EventDispatcher implements IFakeDisplayObject
	{
		private var _url:String;
		private var _loader: BulkLoader;
		private var _loadercontext: LoaderContext;
		
		public function AssetLoader(url:String,  lc:LoaderContext = null ) 
		{
			_url = url;
			_loader = new BulkLoader("loader");
			_loadercontext = lc;
		}
	   
		/**
		 * loads an swf or image file from the specified url. if you specified it already in the constructor you can omit it.
		 */
		public function load():void
		{
			if (_loader.isRunning) return;
			
			_loader.add(_url, {id:"loadedclip", context:_loadercontext});
			_loader.addEventListener(BulkLoader.COMPLETE, onLoadEnds);
			_loader.addEventListener(BulkLoader.PROGRESS, delegate);
			
			_loader.start();
			onLoadStarts();
		}
	   
		/**
		 * unloads the loaded data
		 */
		public function unload():void
		{
			_loader.removeAll();
		}
	   
		/**
		 * stops the download of the cssfile
		 */
		public function stop():void
		{
			if(_loader.isRunning)
				_loader.pauseAll();
		}
	   
		/**
		 * returns the loader instance that has loaded the swf/image from the given url
		 */
		public function getDisplayObject():DisplayObject
		{
			if (!_loader.isFinished) {
				throw new Error("not finished loading");
				return null;
			}
			
			return _loader.getMovieClip("loadedclip");
		}
	   
		/**
		 * returns the loader instance that has loaded the swf/image from the given url
		 */
		public function getDefinitionOf(class_name:String):Class
		{
			if (!_loader.isFinished) {
				throw new Error("not finished loading");
				return null;
			}
			
			return _loader.getMovieClip("loadedclip").loaderInfo.applicationDomain.getDefinition(class_name) as Class; 
		}

	   
		/**
		 * simply delegates the event
		 */
		private function delegate( event:Event ):void
		{
			dispatchEvent(event);
		}
		
		/**
		 * should be called when the load starts
		 */
		private function onLoadStarts( e:Event = null ):void
		{
			if( e != null ) dispatchEvent(e);
		}
	   
		/**
		 * should be called when the load is finished
		 */
		private function onLoadEnds( e:Event = null ):void
		{
			dispatchEvent( new Event(Event.COMPLETE) );
		}
		
	}
	
}